# -*- coding:utf-8 -*-
"""
无边框模式下的自定义标题栏
"""
from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtWidgets import QWidget

from LibrarySystem.config.config import Config

from LibrarySystem.views.ui.TitleBar import Ui_TitleBar


class TitleBar(QWidget, Ui_TitleBar):
    """
    @ClassName：TitleBar
    @Description： 本项目 TitleBar 只有一个实例
     负责无边框模式下，创建自定义标题栏，
     必须接收主窗口实例，用于控制窗体位置移动
    @Author：锦沐Python
     """
    def __init__(self, parent_window=None):
        super().__init__()
        self.setupUi(self)
        self.config = Config()
        if self.config.TitleBar_QSS:
            self.setStyleSheet(self.config.TitleBar_QSS)
        self.parent_window = parent_window

        # 设置鼠标跟踪判断扳机默认值
        self.parent_window.move_drag = False

        # 最小化
        self.min_button.clicked.connect(lambda: self.parent_window.showMinimized())

        # 最大化
        self.max_button.clicked.connect(lambda: self.parent_window.showNormal()
                                        if self.parent_window.isMaximized()
                                        else self.parent_window.showMaximized()
                                        )

        # 关闭程序
        self.close_button.clicked.connect(lambda: self.parent_window.close())

    def move(self, pos):
        super(TitleBar, self.parent_window).move(pos)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.Enter or event.type() == QEvent.Leave:
            self.setCursor(Qt.ArrowCursor)
            return True
        return super().eventFilter(obj, event)

    def mousePressEvent(self, event):
        # 重写鼠标点击的事件
        if event.button() == Qt.LeftButton:
            if event.y() < self.TopBar_widget.height():
                # 鼠标左键点击标题栏区域
                self.parent_window.move_drag = True
                self.parent_window.move_DragPosition = event.globalPos() - self.parent_window.pos()
                event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton:
            # 处理按下左键后的拖动或调整大小操作
            if self.parent_window.move_drag:
                self.parent_window.move(event.globalPos() - self.parent_window.move_DragPosition)
                event.accept()
        else:
            self.setCursor(Qt.ArrowCursor)

    def mouseReleaseEvent(self, QMouseEvent):
        # 鼠标释放后，各扳机复位
        self.parent_window.move_drag = False
